package com.android.takeaway.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import com.android.takeaway.bean.User;


// 用户表的数据库操作对象
public class UserDao {
    private Context context;         // 上下文
    private MyDBOpenHelper dbHelper; // 数据库访问对象
    private SQLiteDatabase database; // 可对数据库进行读写的操作对象

    public UserDao(Context context) {
        this.context = context;
    }

    // 创建并打开数据库（如果数据库已存在直接打开）
    public void open() throws SQLiteException {
        dbHelper = new MyDBOpenHelper(context);
        try {
            database = dbHelper.getWritableDatabase();
        } catch (SQLiteException exception) {
            database = dbHelper.getReadableDatabase();
        }
    }

    // 关闭数据库
    public void close() {
        if (database != null) {
            database.close();
            database = null;
        }
    }

    // 添加用户信息
    public void addUser(User user) {
        ContentValues values = new ContentValues();
        values.put("account", user.getAccount());
        values.put("password", user.getPassword());
        database.insert("User", null, values);
    }

    // 删除用户信息
    public void deleteUser(User user) {
        database.delete("User", "account = ?", new String[]{user.getAccount()});
    }

    // 修改用户信息
    public void updateUser(User user) {
        ContentValues values = new ContentValues();
        values.put("password", user.getPassword());
        database.update("User", values, "account = ?", new String[]{user.getAccount()});
    }

    // 查询用户信息
    public boolean queryUser(User user) {
        // 查询user表中where指定列元素的记录
        Cursor cursor = database.query("User", null, "account = ?", new String[]{user.getAccount()}, null, null, null);
        if (cursor == null || cursor.getCount() < 1) {
            cursor.close();
            return false;
        }
        cursor.close();
        return true;
    }

    // 判断账号是否存在
    public boolean isExist(String account) {
        Cursor cursor = database.query("User", null, "account = ?", new String[]{account}, null, null, null);
        return cursor != null && cursor.getCount() > 0;
    }

    // 根据账号来查找用户密码，登录时校验密码
    public String getPassword(String account) {
        Cursor cursor = database.query("User", null, "account = ?", new String[]{account}, null, null, null);
        cursor.moveToFirst();
        String password = cursor.getString(cursor.getColumnIndex("password"));
        cursor.close();
        return password;
    }

}